"""
udp 服务端流程示例
"""
from socket import *
import pymysql

class Dict:
    def __init__(self):
        # 参数字典
        self.kwargs = {
            "host": "localhost",
            "port": 3306,
            "user": "root",
            "password": "root",
            "database": "dict",
            "charset": "utf8"
        }
        # 连接数据库
        self.db = pymysql.connect(**self.kwargs)
        # 生成游标：执行sql操作数据，得到操作结果的对象
        self.cur = self.db.cursor()
        # 创建udp套接字
        self.udp_socket = socket(AF_INET, SOCK_DGRAM)


    def queryAndSendDict(self):
        # 绑定地址
        self.udp_socket.bind(("0.0.0.0", 8888))
        # 先收后发
        while True:
            data, addr = self.udp_socket.recvfrom(1024)
            try:
                sql = "select menu from dict where word = %s"
                self.cur.execute(sql, [data.decode()])
                fetchone = self.cur.fetchone()
                print(fetchone)
                print(addr, ":", data.decode())  # data->byte
                self.udp_socket.sendto(fetchone[0].encode(), addr)  # addr回复
            except Exception as e:
                print(e)
                self.db.rollback()
            else:
                self.db.commit()  # 提交事务

            # if data.decode() == "##":
            #     break

        #self.udp_socket.close()

if __name__ == '__main__':
    dict = Dict()
    dict.queryAndSendDict()
